// pages/login/login.js
import {
  format
} from "../../utils/util"
import {
  login
} from '../../api/index'


Page({

  /**
   * 页面的初始数据
   */
  data: {
    //登录信息
    loginUserInfo: {
      tel: '',
      pass: ''
    },
  },
  onLoad() {
    const tel = wx.getStorageSync('tel')
    const pass = wx.getStorageSync('pass')
    if (tel && pass) {
      const obj = {
        tel: tel,
        pass: pass
      }
      this.setData({
        loginUserInfo: obj
      })
    }
  },
  // 前往注册页
  toUserInfo() {
    wx.navigateTo({
      url: "/pages/my/registered/registered",
    })
  },
  // 手机号
  onTel(e) {
    console.log("电话：", e.detail.value, format('tel', e.detail.value));
    if (format('tel', e.detail.value)) {
      let obj = JSON.parse(JSON.stringify(this.data.loginUserInfo))
      obj.tel = e.detail.value
      this.setData({
        loginUserInfo: obj
      })
    } else {
      let obj = JSON.parse(JSON.stringify(this.data.loginUserInfo))
      obj.tel = ''
      this.setData({
        loginUserInfo: obj
      })
    }
  },
  // 密码
  onPass(e) {
    console.log("密码：", e.detail.value);
    let obj = JSON.parse(JSON.stringify(this.data.loginUserInfo))
    obj.pass = e.detail.value

    this.setData({
      loginUserInfo: obj
    })
  },

  // 登录
  async onLogin() {
    let loginObj = this.data.loginUserInfo
    if (!loginObj.tel) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号',
      })
      return
    }
    if (!loginObj.pass) {
      wx.showToast({
        icon: 'none',
        title: '请输入密码',
      })

      return
    }
    // 缓存
    try {
      const dataObj = await login({
        phone: loginObj.tel,
        password: loginObj.pass
      })

      console.log("返回对象：", dataObj);
      if (dataObj.code == 200) {
        wx.setStorageSync('token', dataObj.token)
        wx.setStorageSync('userInfo', JSON.stringify(dataObj.userinfo))
        wx.setStorageSync('tel', loginObj.tel)
        wx.setStorageSync('pass', loginObj.pass)

        if (dataObj.userinfo.type == '2') {
          // 管理员登陆
          wx.reLaunch({
            url: '/pages/admin/admin?type=2'
          })

        } else {
          // 前台登录
          wx.switchTab({
            url: '/pages/index/index?type=1'
          })
        }
      }

    } catch (error) {
      console.log("登录失败：", error);
    }
  },

})